/**
 *@description 用户操作页面js
 *@author XieXing
 *@date 2020/8/18 22:46
 */
var table, form, layer, laydate, layedit, selectM, selectN, multiSelect;//当前页面全局定义 TODO 继续优化
var module = {
    /**
     *@description url集合
     *@author XieXing
     *@date 2020/8/18 22:45
     */
    URL: {
        getDataListUrl: '/user/getUserList',//获取数据接口
        getRoles: "/role/getRoles",
        saveUrl: "/user/save",//保存用户信息
        updateUrl: '/user/update',//修改用户信息
        exportUrl: "/user/exportUser",
        importUrl: '/user/importUser',
        updateStatusUrl: function (id, status) {//更新用户状态
            return '/user/' + id + '/' + status;
        },
        deleteUrl: function (id) {//删除用户
            return '/user/' + id;
        },
        getRoleIdsByUserId: '/user_authorization/getRoleIdsByUserId'
    },
    /**
     *@description 初始化
     *@author XieXing
     *@date 2020/8/18 22:46
     */
    init: function () {
        layui.extend({
            selectN: '/static/assets/layui-extends/selectN',
            selectM: '/static/assets/layui-extends/selectM'
        }).use(['form', 'table', 'layer', 'laydate', 'layedit', 'upload', 'selectN', 'selectM'], function () {
            table = layui.table;
            form = layui.form;
            layer = layui.layer;
            laydate = layui.laydate;
            layedit = layui.layedit;
            selectM = layui.selectM;
            selectN = layui.selectN;
            var upload = layui.upload;
            var pageData = page.pageData();
            table.render({
                elem: '#datagrid',
                id: 'datagrid',
                url: module.URL.getDataListUrl,
                method: "GET",
                cols: [[
                    {type: 'radio', fixed: 'left'},
                    {type: 'numbers', title: '序号', fixed: "left"},
                    {
                        field: 'userName',
                        title: '姓名',
                        align: 'center',
                        width: '10%'
                    },
                    {
                        field: 'userGender', title: '性别', width: '10%', align: 'center',
                        templet: function (d) {
                            if (d.userGender == 1) {//男
                                return "男";
                            } else if (d.userGender == 2) {//女
                                return "女";
                            } else {
                                return "未填写";
                            }
                        }
                    },
                    {field: 'userAccount', title: '账号', width: '10%'},

                    {
                        field: 'userPhone',
                        title: '电话',
                        align: 'center',
                        width: '10%'
                    },
                    {field: 'userEmail', title: '邮箱', align: 'center', width: '15%'},
                    {field: 'userAddress', title: '地址', align: 'center', width: '10%'},


                    {
                        field: 'userAddTime',
                        title: '添加时间',
                        align: 'center',
                        width: '15%',
                    },
                    {field: 'userSysId', title: '所属系统', align: 'center', width: '10%'},
                    {field: 'userAddby', title: '添加人姓名', align: 'center', width: '10%'},
                    {field: 'userUpdateTime', title: '修改时间', align: 'center', width: '15%'},
                    {field: 'userUpdateby', title: '修改人姓名', align: 'center', width: '10%'},
                    {field: 'userIntroduction', title: '用户简介', align: 'center', width: '10%'},
                    {field: 'userRemark', title: '备注', align: 'center', width: '10%'},
                    {
                        field: 'userType', title: '用户类型', align: 'center', width: '10%',
                        templet: function (d) {
                            if (d.userType == 1) {
                                return "普通用户";
                            } else {
                                return "特殊用户";
                            }
                        }
                    },
                    {
                        field: 'userIsEnabled', title: '状态', align: 'center', width: '12%', fixed: 'right',
                        templet: function (d) {
                            var checked = "";
                            if (d.userIsEnabled == 1) {
                                checked = "checked=true";
                            }
                            return "<input type='checkbox' " + checked + " id=" + d.id + " userName = " + d.userName + " name='userIsEnabled' lay-skin='switch' lay-text='启用|禁用' lay-event='test' lay-filter='switch'>"
                        }
                    }
                ]],
                height: pageData.tableHeight,
                limit: pageData.limit,
                limits: pageData.limits,
                page: true,
                response: {
                    statusCode: 200
                },
                parseData: function (res) { //res 即为原始返回的数据
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.stateInfo, //解析提示文本
                        "count": res.data.total, //解析数据长度
                        "data": res.data.list //解析数据列表
                    };
                },
                done: function (res, rescurr, count) {
                    var perPageMax = $(".layui-laypage-limits select option:last-child").val();//每页最大条数
                    page.tableLoadAll(count, perPageMax);//加载全部
                }
            });
            /**
             *@description 监听表格中的switch
             *@author XieXing
             *@date 2020/8/18 22:48
             */
            form.on('switch(switch)', function (data) {
                var userId = $(this).attr("id");
                var status = data.elem.checked ? 1 : 0;
                var loading = layer.load(1);
                $.post(module.URL.updateStatusUrl(userId, status), {}, function (result) {
                    if (result && result.code === 200) {
                        layer.closeAll();
                        $("#btnSearch").trigger("click");
                    } else {
                        layer.close(loading);
                        layer.msg(result.err, {icon: 2, time: 2000});
                        return false;
                    }
                });
            });

            /**
             *@description 查询
             *@author XieXing
             *@date 2020/12/10 13:51
             */
            //指定允许上传的文件类型
            upload.render({
                elem: '#importBtn'
                , url: module.URL.importUrl //改成您自己的上传接口
                , accept: 'file' //普通文件
                , done: function (res) {
                    layer.confirm(res.stateInfo, {icon: 1}, function () {

                    });
                }
            });

            /**
             *@description 获取角色
             *@author XieXing
             *@date 2020/10/12 14:13
             */
            $.get(module.URL.getRoles, {}, function (result) {
                if (result.code == 200) {
                    var data = result.data;
                    //多选标签-所有配置
                    multiSelect = selectM({
                        //元素容器【必填】
                        elem: '#roles'
                        //候选数据【必填】
                        , data: data
                        //默认值
                        , selected: []
                        //最多选中个数，默认5
                        , max: data.length
                        //input的name 不设置与选择器相同(去#.)
                        , name: 'roles'
                        //值的分隔符
                        , delimiter: ','
                        //候选项数据的键名
                        , field: {idName: 'id', titleName: 'roleName'}
                    });
                } else {
                    layer.msg(result.stateInfo, {icon: 2, time: 2000});
                }
            });
            /**
             *@description 点击查询
             *@author XieXing
             *@date 2020/7/30 11:34
             */
            $("#btnSearch").on("click", function () {
                var qm = {};
                $("#queryForm").serializeArray().forEach(function (each) {
                    qm[each.name] = each.value;
                });
                var cur = parseInt($(".layui-laypage-skip input").val()) || 1;//当前页
                var limit = parseInt($(".layui-laypage-limits select").val()) || 10;//当前每页条数
                table.reload('datagrid', {
                    where: qm,
                    page: {curr: cur, limit: limit}
                });
                return false;
            });

            /**
             *@description 重置
             *@author XieXing
             *@date 2020/8/16 18:08
             */
            $("#btnReset").click(function () {
                $("#queryForm")[0].reset();
                $("#btnSearch").trigger("click");//触发查询操作
            });

            /**
             *@description 点击新增
             *@author XieXing
             *@date 2020/8/16 16:55
             */
            $("#btnAdd").click(function () {
                module.edit_model("新增用户信息", module.URL.saveUrl);
            });

            /**
             *@description 用户信息导出
             *@author XieXing
             *@date 2020/12/10 9:44
             */
            $("#exportBtn").click(function () {
                window.open(module.URL.exportUrl);
            });

            /**
             *@description 修改用户信息
             *@author XieXing
             *@date 2020/8/17 14:59
             */
            $("#btnUpdate").click(function () {
                var rowData = table.checkStatus('datagrid').data;
                if (rowData.length === 0) {
                    layer.msg("请至少选择一条数据。", {icon: 5, time: 2000});
                    return false;
                }
                rowData = rowData[0];
                module.edit_model("修改用户信息", module.URL.updateUrl, rowData);
            });

            /**
             *@description 删除用户
             *@author XieXing
             *@date 2020/8/17 22:32
             */
            $("#btnDelete").click(function () {
                var rowData = table.checkStatus('datagrid').data;
                if (rowData.length === 0) {
                    layer.msg("请至少选择一条数据。", {icon: 5, time: 2000});
                    return false;
                }
                rowData = rowData[0];
                layer.confirm("确认删除用户" + rowData.userName + "吗？", function () {
                    var loading = layer.load(1);
                    $.post(module.URL.deleteUrl(rowData.id), {}, function (result) {
                        if (result && result.code === 200) {
                            layer.closeAll();
                            $("#dataModel form")[0].reset();
                            $("#btnSearch").trigger("click");
                        } else {
                            layer.close(loading);
                            layer.msg(result.err, {icon: 2, time: 2000});
                            return false;
                        }
                    });
                });

            });
        });
    },

    /**
     *@description 编辑弹出层
     *@author XieXing
     *@date 2020/8/18 22:00
     */
    edit_model: function (modelName, url, rowData) {
        layer.open({
            type: 1,
            area: ['80%', '60%'],
            title: modelName,
            content: $("#dataModel"),
            offset: ['20px'],
            btn: ['提交', '取消'],
            btn1: function (index, layero) {
                $("#formSubmitBtn").trigger("click");
                multiSelect.set([]);
                return false;
            },
            btn2: function (index, layero) {
                $("#dataModel form")[0].reset();
                multiSelect.set([]);
                layer.closeAll();
                return false;
            },
            cancel: function (layero, index) {
                $("#dataModel form")[0].reset();
                multiSelect.set([]);
                layer.closeAll();
            },
            success: function (layero, index) {

                var systemId = "";//默认系统id
                if (rowData) {
                    module.getData(rowData);//非新增操作回填数据

                    // 获取系统下拉框
                    systemId = rowData.userSysId;
                    /**
                     *@description 获取当前用户的角色
                     *@author XieXing
                     *@date 2020/10/13 17:03
                     */
                    $.post(module.URL.getRoleIdsByUserId, {userId: rowData.id}, function (result) {
                        multiSelect.set(result);
                    });
                    $("#userPassword").val("");
                    form.render();

                }
                common.getSystems("userSysId", systemId);
                form.on('submit(form_submit_btn)', function (data) {
                    ;
                    var data = data.field;
                    if (rowData) { //rowData 存在表示修改用户信息
                        data.id = rowData.id;
                        if (rowData.userPassword == data.userPassword) {
                            data.userPassword = null;//发现密码未被修改 就不对密码进行操作
                        }
                    }
                    data.roles = multiSelect.values.join(",");
                    data.userGender = $("input[name=userGender_t]:checked").val();
                    var loading = layer.load(1);
                    $.post(url, data, function (result) {
                        if (result && result.code === 200) {
                            layer.closeAll();
                            $("#dataModel form")[0].reset();
                            $("#btnSearch").trigger("click");
                            multiSelect.set([]);
                        } else {
                            layer.close(loading);
                            layer.msg(result.err, {icon: 2, time: 2000});
                            return false;
                        }
                    });
                    return false;
                });
            }
        });
    },
    /**
     *@description 对象回填数据
     *@author XieXing
     *@date 2020/8/17 15:02
     */
    getData: function (data) {
        for (var k in data) {
            $("input[name=" + k + "],select[name=" + k + "],textarea[name=" + k + "]").val(data[k]);
        }
        $("input[type=radio][value=" + data['userGender'] + "]").attr("checked", "checked");//给单选框赋值
        if (data.userIsEnabled == 1) {
            $("input[type=checkbox]").attr("checked", true);//给单选框赋值
        } else {
            $("input[type=checkbox]").attr("checked", false);//给单选框赋值
        }
        form.render();
    }
};

module.init();//运行初始化函数